package javaLearning.动态代理;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 调用Enhancer来创建代理对象
 * @author : K k
 * @date : 11:17 2020/8/25
 */
public class CglibProxy implements MethodInterceptor {
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("++++++before " + methodProxy.getSuperName() + "++++++");
        //System.out.println(method.getName());
        Object o1 = methodProxy.invokeSuper(o, args);
        System.out.println("++++++before " + methodProxy.getSuperName() + "++++++");
        return o1;
    }

    public static void main(String[] args) {
        //Enhancer是Cglib代理的核心类
        Enhancer enhancer = new Enhancer();
        //作用在类身上，该类最好是不能是接口
        enhancer.setSuperclass(UserServiceImpl.class);
        enhancer.setCallback(new CglibProxy());
        UserService userService = (UserServiceImpl)enhancer.create();
        userService.getAge(1);
    }
}
